layui.use(['table', 'form', 'transfer', 'upload', 'laydate'], function () {
    //获取iframe的body元素
    var body = document.body
    var form = layui.form;
    var transfer = layui.transfer;
    var upload = layui.upload;
    var table = layui.table;
    var laydate = layui.laydate
    form.on('select(search)', function (obj) {
        $(".searchTable .layui-btn").click();
    })
    table.render({
        elem: '#pushList',
        url: '/pushGrade/list',
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        method: "get",
        request: {
            pageName: 'page', //页码的参数名称，默认：page
            limitName: 'limit' //每页数据量的参数名，默认：limit
        },
        parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": 0, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.totalCount, //解析数据长度
                "data": res.data.list //解析数据列表
            }
        },
        cellMinWidth: 80,//全局定义常规单元格的最小宽度，layui 2.2.1 新增
        where: {
            year: new Date().getFullYear()
        },
        page: true,
        loading: true,
        limit: 10,
        limits: [10, 20, 30],
        text: {
            none: '暂无相关数据！'//默认无数据
        },
        cols: [
            [{
                field: 'name',
                align: 'center',
                title: '机关单位名称',
                sort: true
            }, {
                field: 'person',
                align: 'center',
                title: '未完成评分人数'
            }, {
                field: 'scoreS',
                align: 'center',
                title: '非常满意人数',
                sort: true
            }, {
                field: 'scoreA',
                align: 'center',
                title: '满意人数',
                sort: true
            }, {
                field: 'scoreB',
                align: 'center',
                title: '基本满意人数',
                sort: true
            }, {
                field: 'scoreC',
                align: 'center',
                title: '不满意人数',
                sort: true
            }, {
                field: 'startTime',
                align: 'center',
                title: '开始时间',
                templet: function (d) {
                    return layui.util.toDateString(d.startTime, "yyyy-MM-dd")
                }
            }, {
                field: 'endTime',
                align: 'center',
                title: '结束时间',
                templet: function (d) {
                    return layui.util.toDateString(d.endTime, "yyyy-MM-dd")
                }
            }, {
                fixed: 'right',
                title: '操作',
                toolbar: '#barDemo'
            }]
        ]
    });

    table.on('row(pushList)', function (obj) {
        var data = obj.data;
        $("#show").html(data.name + data.year + "年满意度详情")
        table.render({
            elem: '#personList',
            url: '/grade/personList',
            toolbar: '#toolbarDemo1', //开启头部工具栏，并为其绑定左侧模板
            method: "get",
            request: {
                pageName: 'page', //页码的参数名称，默认：page
                limitName: 'limit', //每页数据量的参数名，默认：limit
                pushUid: data.pushUid
            },
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.totalCount, //解析数据长度
                    "data": res.data.list //解析数据列表
                }
            },
            cellMinWidth: 100,//全局定义常规单元格的最小宽度，layui 2.2.1 新增
            where: {
                pushUid: data.pushUid
            },
            page: true,
            loading: true,
            limit: 10,
            limits: [10, 30, 1000],
            text: {
                none: '暂无相关数据！'//默认无数据
            },
            cols: [
                [{
                    field: 'departmentName',
                    align: 'center',
                    title: '教学单位',
                    sort: true,
                    width: '15%'
                }, {
                    field: 'personName',
                    align: 'center',
                    title: '姓名',
                    width: '10%'
                }, {
                    field: 'score',
                    align: 'center',
                    title: '满意度',
                    width: '10%',
                    sort: true,
                    templet: function (d) {
                        if (d.status == "0") {
                            return '<span style="color:#ee0043;"><strong>未评价</strong></span>'
                        }
                        if (d.score == '1') {//不满意
                            return '<span style="color:#f5275d;"><strong>不满意</strong></span>'
                        }
                        if (d.score == '2') {//基本满意
                            return '<span style="color:#9689f1;"><strong>基本满意</strong></span>'
                        }
                        if (d.score == '3') {//满意
                            return '<span style="color:#0bb3f8;"><strong>满意</strong></span>'
                        }
                        if (d.score == '4') {//满意
                            return '<span style="color:#2cef1a;"><strong>非常满意</strong></span>'
                        }
                    }
                }, {
                    field: 'completeTime',
                    align: 'center',
                    title: '评价时间',
                    width: '15%'
                }, {
                    field: 'context',
                    align: 'center',
                    title: '评价内容',
                    width: '50%'
                }]
            ],
            done: function (res, curr, count) {
                $('table').css('width', '100%');
//这里设置表格的宽度为100%
            }
        });


        //标注选中样式
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
    });

    var $ = layui.$, active = {
        reload: function () {
            //查询条件组装
            var queryWhere = {};
            queryWhere['year'] = $("#year").find("option:selected").val();
            //执行重载
            table.reload('pushList', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                , where: queryWhere
                , done: function (res, curr, count) {
                    this.where = queryWhere;
                }
            }, 'data');
            var value = $(body).find("#status").val()
            if (value == 0) {
                $(body).find("#delBtn")[0].style.display = "none"
                $(body).find("#isTBtn")[0].style.display = "inline-block"
                $(body).find("#cDeleteBtn")[0].style.display = "inline-block"
            } else if (value == 1) {
                $(body).find("#delBtn")[0].style.display = "inline-block"
                $(body).find("#isTBtn")[0].style.display = "none"
                $(body).find("#cDeleteBtn")[0].style.display = "none"
            }
        },
        getCheckData: function () { //获取选中数据
            var checkStatus = table.checkStatus('pushList')
                , data = checkStatus.data;
            layer.alert(JSON.stringify(data));
        }
        , getCheckLength: function () { //获取选中数目
            var checkStatus = table.checkStatus('pushList')
                , data = checkStatus.data;
            layer.msg('选中了：' + data.length + ' 个');
        }
        , isAll: function () { //验证是否全选
            var checkStatus = table.checkStatus('pushList');
            layer.msg(checkStatus.isAll ? '全选' : '未全选')
        }
    };

    $('.searchTable .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    laydate.render({
        elem: '#time'
        //设置开始日期、日期日期的 input 选择器
        //数组格式为 2.6.6 开始新增，之前版本直接配置 true 或任意分割字符即可
        , range: ['#test-startDate-1', '#test-endDate-1']
    });

    laydate.render({
        elem: '#timeAll'
        //设置开始日期、日期日期的 input 选择器
        //数组格式为 2.6.6 开始新增，之前版本直接配置 true 或任意分割字符即可
        , range: ['#test-startDate-All', '#test-endDate-All']
    });

    //头部工具栏
    table.on('toolbar(pushList)', function (obj) {
        switch (obj.event) {
            case 'add': {
                document.getElementById("commentForm").reset();
                $("#showName").html("");
                $("#uid").removeAttr("disabled");
                form.render();
                $(body).find("#uid").val("");
                var addOpen = layer.open({
                    //基本层类型
                    type: 1,
                    shadeClose: false,
                    scrollbar: false,
                    area: ['750px', '490px'],
                    //标题
                    title: '创建新任务',
                    //内容
                    content: $('#commentForm'),
                    //按钮
                    btn: ['创建', '取消'],
                    //确定按钮
                    yes: () => {
                        if (validateCode()) {
                            //开启loading
                            const loading = layer.load(2);
                            //获取表单内的所有值
                            var formObj = form.val('pushForm');
                            //发送数据到接口
                            $.ajax({
                                url: '/pushGrade/save',
                                method: "post",
                                contentType: 'application/json;charset=utf-8',
                                data: JSON.stringify(formObj),
                                dataType: "json",
                                success: function (data) {
                                    layer.close(loading);
                                    if (data.code == 200) {
                                        layer.msg("创建成功");
                                        layer.close(addOpen)
                                        $(".searchTable .layui-btn").click();
                                    } else {
                                        layer.alert(data.msg);
                                    }
                                }
                            });
                        }
                    },
                });
            }
                break;
            case 'addAll': {
                var addOpen = layer.open({
                    //基本层类型
                    type: 1,
                    shadeClose: false,
                    scrollbar: false,
                    area: ['750px', '300px'],
                    //标题
                    title: '创建批量任务-对所有可用单位发起',
                    //内容
                    content: $('#commentFormAll'),
                    //按钮
                    btn: ['创建', '取消'],
                    //确定按钮
                    yes: () => {
                        if (validateCodeAll()) {
                            //开启loading
                            const loading = layer.load(2);
                            //获取表单内的所有值
                            var formObj = form.val('commentFormAll');
                            //发送数据到接口
                            $.ajax({
                                url: '/pushGrade/saveAll',
                                method: "post",
                                contentType: 'application/json;charset=utf-8',
                                data: JSON.stringify(formObj),
                                dataType: "json",
                                success: function (data) {
                                    layer.close(loading);
                                    if (data.code == 200) {
                                        layer.msg("创建成功！共创建任务为：" + data.data);
                                        layer.close(addOpen)
                                        $(".searchTable .layui-btn").click();
                                    } else {
                                        layer.alert(data.msg);
                                    }
                                }
                            });
                        }
                    },
                });
            }
                break;
            case 'count': {
                var addOpen = layer.open({
                    //基本层类型
                    type: 1,
                    shadeClose: false,
                    scrollbar: false,
                    area: ['300px', '300px'],
                    //标题
                    title: '编辑评价次数',
                    //内容
                    content: $('#countForm'),
                    //按钮
                    btn: ['确定', '取消'],
                    //确定按钮
                    yes: () => {
                        if (validateCount()) {
                            //开启loading
                            const loading = layer.load(2);
                            //获取表单内的所有值
                            var formObj = form.val('countForm');
                            //发送数据到接口
                            $.ajax({
                                url: '/pushGrade/count',
                                method: "post",
                                contentType: 'application/json;charset=utf-8',
                                data: JSON.stringify(formObj),
                                dataType: "json",
                                success: function (data) {
                                    layer.close(loading);
                                    if (data.code == 200) {
                                        layer.msg("修改成功！");
                                        layer.close(addOpen)
                                    } else {
                                        layer.alert(data.msg);
                                    }
                                    setTimeout(function () {
                                        window.location.href = getRootPath() + '/pushGrade'
                                    }, 1000);
                                }
                            });
                        }
                    },
                });
            }
                break;
            case 'context': {
                var addOpen = layer.open({
                    //基本层类型
                    type: 1,
                    shadeClose: false,
                    scrollbar: false,
                    area: ['750px', '300px'],
                    //标题
                    title: '编辑公告',
                    //内容
                    content: $('#contextForm'),
                    //按钮
                    btn: ['确定', '取消'],
                    //确定按钮
                    yes: () => {
                        //开启loading
                        const loading = layer.load(2);
                        //获取表单内的所有值
                        var formObj = form.val('contextForm');
                        //发送数据到接口
                        $.ajax({
                            url: '/pushGrade/context',
                            method: "post",
                            contentType: 'application/json;charset=utf-8',
                            data: JSON.stringify(formObj),
                            dataType: "json",
                            success: function (data) {
                                layer.close(loading);
                                if (data.code == 200) {
                                    layer.msg("更新成功！");
                                    layer.close(addOpen)
                                } else {
                                    layer.alert(data.msg);
                                }
                            }
                        });

                    },
                });
            }
                break;
            // case 'isTAll': {
            //     layer.confirm('确定恢复么？(将移入可用部门)', function (index) {
            //         //开启loading
            //         const loading = layer.load(2);
            //         var paramBody = [], count = 0;
            //         var checkStatus = table.checkStatus('pushList')
            //             , data = checkStatus.data;
            //         data.forEach(function (i) {
            //             paramBody[count++] = i.uid
            //         })
            //         $.ajax({
            //             url: '/push/isT',
            //             method: "post",
            //             contentType: 'application/json;charset=utf-8',
            //             data: JSON.stringify(paramBody),
            //             dataType: "json",
            //             success: function (res) {
            //                 layer.close(loading);
            //                 if (res.code == 200) {
            //                     layer.alert("成功!");
            //                     $(".searchTable .layui-btn").click();
            //                 } else {
            //                     layer.alert(res.msg);
            //                 }
            //             }
            //         });
            //         layer.close(index);
            //     });
            // }
            //     break;
            // case 'cDelete': {
            //     layer.confirm('确定彻底删除么？(将删除这些部门以及其下的所有账号)', function (index) {
            //         //开启loading
            //         const loading = layer.load(2);
            //         var paramBody = [], count = 0;
            //         var checkStatus = table.checkStatus('pushList')
            //             , data = checkStatus.data;
            //         data.forEach(function (i) {
            //             paramBody[count++] = i.uid
            //         })
            //         $.ajax({
            //             url: '/push/cDelete',
            //             method: "post",
            //             contentType: 'application/json;charset=utf-8',
            //             data: JSON.stringify(paramBody),
            //             dataType: "json",
            //             success: function (res) {
            //                 layer.close(loading);
            //                 if (res.code == 200) {
            //                     layer.alert("成功!");
            //                     $(".searchTable .layui-btn").click();
            //                 } else {
            //                     layer.alert(res.msg);
            //                 }
            //             }
            //         });
            //         layer.close(index);
            //     });
            // }
            //     break;
        }
    });

    //监听工具条
    table.on('tool(pushList)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('真的删除么？(将移入不可用部门)', function (index) {
                //开启loading
                const loading = layer.load(2);
                var paramBody = []
                paramBody[0] = data.uid;
                $.ajax({
                    url: '/pushGrade/delete',
                    method: "post",
                    contentType: 'application/json;charset=utf-8',
                    data: JSON.stringify(paramBody),
                    dataType: "json",
                    success: function (res) {
                        layer.close(loading);
                        if (res.code == 200) {
                            layer.msg("删除成功!");
                            obj.del();
                        } else {
                            layer.alert(res.msg);
                        }
                    }
                });
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            data.departmentUid = data.uid
            form.val('pushForm', data);
            $("#uidText").html(data.uid)
            $("#pushUid").val(data.pushUid)
            $("#uid").attr("disabled", "disabled");
            form.render();
            var editOpen = layer.open({
                //基本层类型
                type: 1,
                shadeClose: false,
                scrollbar: false,
                area: ['750px', '350px'],
                //标题
                title: '编辑任务',
                //内容
                content: $('#commentForm'),
                //按钮
                btn: ['修改', '取消'],
                //确定按钮
                yes: () => {
                    if (validateCode()) {
                        //开启loading
                        const loading = layer.load(2);
                        //获取表单内的所有值
                        var formObj = form.val('pushForm');
                        //发送数据到接口
                        $.ajax({
                            url: '/pushGrade/update',
                            method: "post",
                            contentType: 'application/json;charset=utf-8',
                            data: JSON.stringify(formObj),
                            dataType: "json",
                            success: function (data) {
                                layer.close(loading);
                                if (data.code == 200) {
                                    layer.msg("修改成功!");
                                    layer.close(editOpen)
                                    $(".searchTable .layui-btn").click();
                                } else {
                                    layer.alert(data.msg);
                                }

                            }
                        });
                    }
                }
            });

        }
        // else if (obj.event === 'isT') {
        //     layer.confirm('确定恢复么？(将移入可用部门)', function (index) {
        //         //开启loading
        //         const loading = layer.load(2);
        //         var paramBody = []
        //         paramBody[0] = data.uid;
        //         $.ajax({
        //             url: '/push/isT',
        //             method: "post",
        //             contentType: 'application/json;charset=utf-8',
        //             data: JSON.stringify(paramBody),
        //             dataType: "json",
        //             success: function (res) {
        //                 layer.close(loading);
        //                 if (res.code == 200) {
        //                     layer.alert("成功!");
        //                     obj.del();
        //                 } else {
        //                     layer.alert(res.msg);
        //                 }
        //             }
        //         });
        //         layer.close(index);
        //     });
        // } else if (obj.event === 'cDelete') {
        //     layer.confirm('确定彻底删除么？(将删除这些部门以及其下的所有账号)', function (index) {
        //         //开启loading
        //         const loading = layer.load(2);
        //         var paramBody = []
        //         paramBody[0] = data.uid;
        //         $.ajax({
        //             url: '/push/cDelete',
        //             method: "post",
        //             contentType: 'application/json;charset=utf-8',
        //             data: JSON.stringify(paramBody),
        //             dataType: "json",
        //             success: function (res) {
        //                 layer.close(loading);
        //                 if (res.code == 200) {
        //                     layer.alert("成功!");
        //                     obj.del();
        //                 } else {
        //                     layer.alert(res.msg);
        //                 }
        //             }
        //         });
        //         layer.close(index);
        //     });
        // }
    });

    form.on('select(uid)', function (d) {
        $("#uidText").html(d.value)
    })

    form.on('select(year)', function (d) {
        $("#yearText").html(d.value)
    })

    $.ajax({
        url: '/department/listAll',
        method: 'GET',
        dataType: 'JSON',
        success: function (res) {
            //debugger;
            data2 = res.data;
            //显示搜索框
            //数据格式解析
            transfer.render({
                elem: '#test3',
                data: data2
                , id: 'depUid'
                , parseData: function (res) {
                    return {
                        "uid": res.uid                             //数据值
                        , "title": res.name                          //数据标题
                        , "checked": false//res.checked             //是否选中
                    }
                }
                , title: ['教学单位', '参与评分']
                , showSearch: true
                , height: 410
                , width: 300
            })
        }
    })
});

function validateCount() {
    var s = $("#s").val();
    var bad = $("#bad").val();
    if (s == null || s == "") {
        layer.msg("请输入 【非常满意】 能够评价的最大个数！")
        return false;
    }
    if (bad == null || bad == "") {
        layer.msg("请输入 【不满意】 能够评价的最大个数！")
        return false;
    }
    return true;
}

function validateCodeAll() {
    var year = $("#yearText").html();
    if (year == null || year == "") {
        layer.msg("请选择年份！")
        return false;
    }
    var startTimeAll = $("#test-startDate-All").val();
    if (startTimeAll == null || startTimeAll == "") {
        layer.msg("请选择开始时间！")
        return false;
    }
    var endTimeAll = $("#test-endDate-All").val();
    if (endTimeAll == null || endTimeAll == "") {
        layer.msg("请选择结束时间！")
        return false;
    }

    return true;
}

function validateCode() {
    var year = $("#yearText").html();
    if (year == null || year == "") {
        layer.msg("请选择年份！")
        return false;
    }
    var uid = $("#uidText").html();
    if (uid == null || uid == "") {
        layer.msg("请选择部门！")
        return false;
    }
    var startTime = $("#test-startDate-1").val();
    if (startTime == null || startTime == "") {
        layer.msg("请选择开始时间！")
        return false;
    }
    var endTime = $("#test-endDate-1").val();
    if (endTime == null || endTime == "") {
        layer.msg("请选择结束时间！")
        return false;
    }
    return true;
}

window.onload = function () {
    var year = new Date().getFullYear();
    document.getElementById("yearText").innerHTML = year;
    document.getElementById("formYear").value = year;
    document.getElementById("formYearAll").value = year;
    year += 1;
    for (let i = 0; i < 5; i++) {
        document.getElementById("year").options.add(new Option(year - i, year - i));
    }
    var select = document.getElementById("year")
    select.options[1].selected = true;
    layui.form.render('select');
}

function getRootPath() {
    // 获取当前网址，如：http://localhost:8080/MyWeb/index.html
    var curWwwPath = window.document.location.href;
    // 获取主机地址之后的目录，如： MyWeb/index.html
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    // 获取主机地址，如： http://localhost:8080
    var localhostPath = curWwwPath.substring(0, pos);
    return localhostPath;
}
